package com.randb.easyhttp.cookie;

import android.content.Context;

import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.List;

import okhttp3.Cookie;
import okhttp3.CookieJar;
import okhttp3.HttpUrl;

/**
 * User: RandBII
 * Date: 2020/5/15
 * Description:
 */
public class CookieManager implements CookieJar {

    private static Context mContext;
    private static PersistentCookieStore cookieStore;

    public CookieManager(Context context) {
        mContext = context;
        if (cookieStore == null) cookieStore = new PersistentCookieStore(context);
    }

    public void addCookies(List<Cookie> cookies) {
        cookieStore.addCookies(cookies);
    }

    @NotNull
    @Override
    public List<Cookie> loadForRequest(@NotNull HttpUrl httpUrl) {
        List<Cookie> cookies = cookieStore.get(httpUrl);
        return cookies != null ? cookies : new ArrayList<Cookie>();
    }

    @Override
    public void saveFromResponse(@NotNull HttpUrl httpUrl, @NotNull List<Cookie> list) {
        if (list.size() > 0) {
            for (Cookie cookie : list) {
                cookieStore.add(httpUrl, cookie);
            }
        }

    }
}
